package com.example.h5shell;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.h5shell.http.OkHttpService;
import com.example.h5shell.utils.FileHelper;
import com.example.h5shell.utils.PermissionHelper;
import com.example.h5shell.utils.SmsHelper;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity implements PermissionHelper.PermissionCallback {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置xml样式
        setContentView(R.layout.activity_main);

        // 获取webView元素
        webView = findViewById(R.id.webview);

        //请求回调
        OkHttpService.get("https://www.baidu.com/", new OkhttpCallBack(this));

        // 启用JavaScript
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // 设置WebViewClient来拦截URL加载
        webView.setWebViewClient(new WebViewClient());

        // 设置js接口
        webView.addJavascriptInterface(new WebAppInterface(this), "Android");

        // 加载H5页面
        webView.loadUrl("http://47.109.25.58:8028/");

        Log.d("TAG", "onCreate: ");

    }


    @Override
    public void onPermissionGranted() {
        // 权限请求被用户授予
        System.out.println("onPermissionGranted");

        // 注意：这里假设你的应用已经具有读取短信的权限
        SmsHelper smsReader = new SmsHelper(this);

        List<SmsHelper.Sms> smsList = smsReader.readSmsMessages();
        Log.d("c", smsList.toString());

        // 现在你可以遍历smsList来处理短信数据了
        for (SmsHelper.Sms sms : smsList) {
            Log.d("SMS_READER", "ID: " + sms.id + ", Address: " + sms.address + ", Body: " + sms.body + ", Date: " + sms.date);
        }

    }

    @Override
    public void onPermissionDenied(List<String> deniedPermissions) {
        // 权限请求被用户拒绝
        System.out.println(deniedPermissions);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 你可以根据requestCode来判断是哪个请求的结果，并调用相应的逻辑
        if (requestCode == 100) {
            // 检查是否所有请求的权限都被授予
            boolean allGranted = true;
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }
            if (allGranted) {
                // 所有权限都被授予
                onPermissionGranted(); // 调用你的回调方法
            } else {
                // 至少有一个权限被拒绝
                onPermissionDenied(Arrays.asList(permissions)); // 传递被拒绝的权限列表到你的回调方法
            }
        }
    }


    /**
     * desc: H5控制安卓屏幕转向的问题
     * use: H5使用方法<button onclick="Android.setScreenOrientationLandscape()">Set Landscape</button>
     */
    public class WebAppInterface {
        Context mContext;

        WebAppInterface(Context c) {
            mContext = c;
        }

        /**
         * 设置屏幕竖向
         */
        @JavascriptInterface
        public void setScreenOrientationLandscape() {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        /**
         * 设置屏幕横向
         */
        @JavascriptInterface
        public void setScreenOrientationPortrait() {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }
}


/**
 * desc: 发用请求项目回调
 * use: OkHttpService.get("https://www.baidu.com/", new OkhttpCallBack());
 */

class OkhttpCallBack implements Callback {

    Context mContext;

    OkhttpCallBack(Context c) {
        mContext = c;
    }

    @Override
    public void onFailure(Call call, IOException e) {
        e.printStackTrace();
        // 处理请求失败
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
            String responseBody = response.body().string();

            Log.d("onResponse: ", responseBody);
            // 处理响应数据

            // 写入内部存储
            FileHelper fileHelper = new FileHelper();
            String internalFileName = "internal_data.txt";
            String internalData = "Hello, Internal Storage!";
            fileHelper.writeInternalFile(mContext, internalFileName, internalData);

            // 读取内部存储
            String readInternalData = fileHelper.readInternalFile(mContext, internalFileName);
            System.out.println(readInternalData);
        }
    }
}


